package com.decent.ejfadmin.job;

import com.decent.ejfadmin.common.bean.SupplyConsumption;
import com.decent.ejfadmin.common.bean.SupplyDailySheet;
import com.decent.ejfadmin.common.enums.Operator;
import com.decent.ejfadmin.finance.dao.SupplyDailySheetDao;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 供货日报表定时器
 *
 * @author 王元鑫
 * @date 2016/8/19
 */
@Component
@Configurable
@EnableScheduling
@Slf4j
public class SupplyDailySheetJob {
	@Autowired
	private SupplyDailySheetDao supplyDailySheetDao;

	String yyyyMMdd = "yyyy-MM-dd";

	/**
	 * 每天1点
	 */
	@Scheduled(cron = "0 0 1 * * ?")
	public void doScheduledJob() {
		// 查询有供货明细的会员
		List<Long> querySupplyDailySheetUserId = supplyDailySheetDao
				.querySupplyDailySheetUserId(DateFormatUtils.format(DateUtils.addDays(new Date(), -2), yyyyMMdd));
		// 查询有消费明细的会员
		List<Long> queryUserConsumption = supplyDailySheetDao.queryUserConsumption(
				DateFormatUtils.format(DateUtils.addDays(new Date(), -1), "yyyy-MM-dd 00:00:00"),
				DateFormatUtils.format(new Date(), "yyyy-MM-dd 00:00:00"));
		querySupplyDailySheetUserId.addAll(queryUserConsumption);
		List<Long> newUserList = querySupplyDailySheetUserId.stream().distinct().collect(Collectors.toList());
		String time = DateFormatUtils.format(DateUtils.addDays(new Date(), -1), yyyyMMdd); // 时间戳
		for (Long userId : newUserList) {
			try {
				SupplyDailySheet sheet = new SupplyDailySheet();
				sheet.setUserId(userId);
				sheet.setStartTime(time);
				// 期初余额
				SupplyDailySheet tempSheet = supplyDailySheetDao.queryBeginBalance(userId, time);
				if (tempSheet != null) {
					sheet.setBeginBalance(tempSheet.getBeginBalance());
				}
				// 期末余额，查询消费明细
				SupplyConsumption consumption = supplyDailySheetDao.queryUserSupplyConsumption(userId, time, "desc");
				if (consumption == null) {
					// 没有消费明细
					sheet.setEndBalance(sheet.getBeginBalance());
					supplyDailySheetDao.createDailySheet(sheet);
					continue;
				}
				sheet.setEndBalance(consumption.getBalance());
				// 提现金额（支付宝）
				tempSheet = supplyDailySheetDao.queryWithdrawMoney(userId, time);
				if (tempSheet != null) {
					sheet.setWithdrawMoney(tempSheet.getWithdrawMoney());
				}
				// 提现金额（银行卡）
				tempSheet = supplyDailySheetDao.queryWithdrawBankMoney(userId, time);
				if (tempSheet != null) {
					sheet.setWithdrawBankMoney(tempSheet.getWithdrawBankMoney());
					sheet.setServicePrice(tempSheet.getServicePrice());
				}
				// 补结金额(三网+虚商)
				tempSheet = supplyDailySheetDao.queryFixMoney(userId, time);
				if (tempSheet != null) {
					sheet.setFixMoney(tempSheet.getFixMoney());
				}
				// 补结金额(加油卡)
				tempSheet = supplyDailySheetDao.queryFixFuelMoney(userId, time);
				if (tempSheet != null) {
					sheet.setFixFuelMoney(tempSheet.getFixFuelMoney());
				}
				// 补结金额(权益)
				tempSheet = supplyDailySheetDao.queryFixEquityMoney(userId, time);
				// 补扣款金额(权益)
				SupplyDailySheet fixDeductEquitySheet = supplyDailySheetDao.queryFixDeductEquityMoney(userId, time);
				if (tempSheet != null) {
					// 补结-补扣款
					sheet.setFixEquityMoney(
							tempSheet.getFixEquityMoney().subtract(fixDeductEquitySheet.getFixEquityMoney()));
				}
				// 返佣=返佣+手动补结算+补差额金额+补手续费
				tempSheet = supplyDailySheetDao.queryRebate(userId, time);
				if (tempSheet != null) {
					sheet.setRebate(tempSheet.getRebate());
				}
				// 手动退款
				tempSheet = supplyDailySheetDao.queryManualRefund(userId, time);
				if (tempSheet != null) {
					sheet.setManualRefund(tempSheet.getManualRefund());
				}
				// 运营商成功、入账金额
				List<Map<String, Object>> productTypeSummary = supplyDailySheetDao.querySummary(userId, time);
				List<SupplyDailySheet> agentNoSummarys = supplyDailySheetDao.querySummaryByAgentNo(userId, time);
				agentNoSummarys.forEach(agentNoSummary -> {
					if ("EJF".equals(agentNoSummary.getAgentNo())) {
						sheet.setEjfMoney(agentNoSummary.getEntryMoney());
					} else if ("EASY".equals(agentNoSummary.getAgentNo())) {
						sheet.setEasyServerMoney(agentNoSummary.getEntryMoney());
					}
				});
				for (Map<String, Object> resultMap : productTypeSummary) {
					Operator operator = Operator
							.matchOperator(Integer.valueOf(resultMap.get("productTypeFlag").toString()));
					switch (operator) {
					case MOBILE:
						sheet.setMobileSuccessFace((BigDecimal) resultMap.get("successFace"));
						sheet.setMobileEntryMoney((BigDecimal) resultMap.get("entryMoney"));
						break;
					case UNICOM:
						sheet.setUnicomSuccessFace((BigDecimal) resultMap.get("successFace"));
						sheet.setUnicomEntryMoney((BigDecimal) resultMap.get("entryMoney"));
						break;
					case TELECOM:
						sheet.setTelecomSuccessFace((BigDecimal) resultMap.get("successFace"));
						sheet.setTelecomEntryMoney((BigDecimal) resultMap.get("entryMoney"));
						break;
					case CNPC:
					case SINOPEC:
					case SINOPEC_NONNUM:
					case CNPC_NONNUM:
						sheet.addFuelSuccessFace((BigDecimal) resultMap.get("successFace"));
						sheet.addFuelEntryMoney((BigDecimal) resultMap.get("entryMoney"));
						break;
					case EQUITY:
						sheet.setEquitySuccessFace((BigDecimal) resultMap.get("equitySuccessFace"));
						sheet.setEquityMoney((BigDecimal) resultMap.get("equityMoney"));
						break;
					default:
						sheet.addVirtualSuccessFace((BigDecimal) resultMap.get("successFace"));
						sheet.addVirtualEntryMoney((BigDecimal) resultMap.get("entryMoney"));
						break;
					}
				}
				// 工号成功面值，金额（计入虚商）
				Map<String, Object> workNumber = supplyDailySheetDao.queryWorkNumberSummary(userId, time);
				if (workNumber != null && !workNumber.isEmpty()) {
					sheet.addVirtualSuccessFace((BigDecimal) workNumber.get("successFace"));
					sheet.addVirtualEntryMoney((BigDecimal) workNumber.get("entryMoney"));
				}
				Map<String, Object> qbOrder = supplyDailySheetDao.queryQbOrderSummary(userId, time);
				if (qbOrder != null && !qbOrder.isEmpty()) {
					sheet.setQbSuccessFace((BigDecimal) qbOrder.get("successFace"));
					sheet.setQbEntryMoney((BigDecimal) qbOrder.get("entryMoney"));
				}
				// 汇总面值，入账（汇总）金额
				sheet.setSummaryFace(sheet.getMobileSuccessFace().add(sheet.getUnicomSuccessFace())
						.add(sheet.getTelecomSuccessFace()).add(sheet.getVirtualSuccessFace())
						.add(sheet.getFuelSuccessFace()).add(sheet.getEquitySuccessFace())
						.add(sheet.getQbSuccessFace()));
				sheet.setEntryMoney(sheet.getMobileEntryMoney().add(sheet.getUnicomEntryMoney())
						.add(sheet.getTelecomEntryMoney()).add(sheet.getVirtualEntryMoney())
						.add(sheet.getFuelEntryMoney()).add(sheet.getEquityMoney()).add(sheet.getQbEntryMoney()));
//                sheet.setRecommendRebate(BigDecimal.ZERO);
				// 差额=期初余额+入账金额+补结金额（话费）+补结金额（加油卡）+补结金额（权益）+返佣+(推荐商户)-提现至支付宝-提现至银行-期末余额-手续费
				sheet.setDefference(sheet.getBeginBalance().add(sheet.getEntryMoney()).add(sheet.getFixMoney())
						.add(sheet.getFixFuelMoney()).add(sheet.getFixEquityMoney()).add(sheet.getRebate())
						.add(sheet.getManualRefund()).subtract(sheet.getWithdrawMoney())
						.subtract(sheet.getWithdrawBankMoney()).subtract(sheet.getEndBalance())
						.subtract(sheet.getServicePrice()));

				supplyDailySheetDao.createDailySheet(sheet);
			} catch (Exception e) {
				log.error("供货日报表定时器异常[{}][{}]", userId, e.getLocalizedMessage(), e);
			}
		}
	}
}
